package com.plan.code;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.plan.entity.UserInfo;

/**
 * @description: IF条件合并提炼
 * @author: admin
 * @time: 2022/12/6 21:36
 */
public class IfElse02 {


    public static void main(String[] args) {
        UserInfo userInfo = UserInfo.builder()
                .id(1)
                .name("小明")
                .isActivated(Boolean.TRUE)
                .status("valid")
                .build();

        //System.out.println(getCheck(userInfo));
        //System.out.println(getCheckOptimization01(userInfo));
        System.out.println(getCheckOptimization02(userInfo));

    }

    /**
     * IF多条件判断
     * @param userInfo
     * @return
     */
    public static String getCheck(UserInfo userInfo) {
        if (StringUtils.isBlank(userInfo.getName())) {
            return "Invalid data received";
        }
        if (userInfo.getId() <= 0) {
            return "Invalid data received";
        }
        if (StringUtils.isBlank(userInfo.getStatus())) {
            return "Invalid data received";
        }
        if (!userInfo.isActivated()) {
            return "User status is not normal";
        }
        if (!"valid".equals(userInfo.getStatus())) {
            return "User status is not normal";
        }
        return "Welcome" + userInfo.getName();
    }

    /**
     * 缩减IF
     * @param userInfo
     * @return
     */
    public static String getCheckOptimization01(UserInfo userInfo) {
        if (StringUtils.isBlank(userInfo.getName())
                || (userInfo.getId() <= 0)
                || (StringUtils.isBlank(userInfo.getStatus()))) {
            return "Invalid data received";
        }
        if (!userInfo.isActivated()
                || (!"valid".equals(userInfo.getStatus()))) {
            return "User status is not normal";
        }
        return "Welcome" + userInfo.getName();
    }

    /**
     * 抽取IF条件为方法,让代码更容易让人理解
     * 但是方法名一定要见名之意
     * @param userInfo
     * @return
     */
    public static String getCheckOptimization02(UserInfo userInfo) {
        if (isDataValid(userInfo)) {
            return "Invalid data received";
        }
        if (isUserStatusNormal(userInfo)) {
            return "User status is not normal";
        }
        return "Welcome" + userInfo.getName();
    }

    /**
     * 用户状态是否正常
     * @param userInfo
     * @return
     */
    private static boolean isUserStatusNormal(UserInfo userInfo) {
        return !userInfo.isActivated()
                || (!"valid".equals(userInfo.getStatus()));
    }

    /**
     * 数据是否有效
     * @param userInfo
     * @return
     */
    private static boolean isDataValid(UserInfo userInfo) {
        return StringUtils.isBlank(userInfo.getName())
                || (userInfo.getId() <= 0)
                || (StringUtils.isBlank(userInfo.getStatus()));
    }
}
